<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2017/6/5
 * Time: 上午10:37
 */

namespace app\api\controller;

use Alipay\Alipayobj;
use app\common\model\Agent;
use app\common\model\CardBonusRule;
use app\common\model\CardConsume;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\CardRank;
use app\common\model\CardUserGet;
use app\common\model\CardUserUpdate;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\WxOpen;
use think\Db;
use Wechat\Wxobjopen;

class HttpPay
{

    public function getpay($data)
    {
        try {
            if ($data['price'] > 0) {
                $Paylog = new Paylog();
                $data['orderid'] = $this->getorder($data['merchid']);
                $orderchack = $Paylog->where(array('orderid' => $data['orderid']))->find();
                if (!$orderchack) {
                    $pays['mid'] = $data['merchid'];
                    $pays['add_time'] = time();
                    $pays['orderid'] = $data['orderid'];
                    $pays['price'] = $data['price'];
                    $pays['yf_price'] = $data['price'];
                    $pays['pay_statu'] = 0;
                    $pays['d_cashier'] = $data['cashier'];
                    $pays['wsy_orderid'] = $data['outTradeNo'];
                    $kt = substr($data['auth_code'], 0, 2);
                    $User = new Merchant();
                    $machinfos = $User->where(array('id' => $data['merchid']))->find();
                    switch ($machinfos['shtd']) {
                        case '0':
                            if ($kt >= 25 && $kt <= 30) {
                                if ($machinfos['ali_merid'] !== '') {
                                    $pays['pay_fs'] = 3;
                                    $Paylog->save($pays);
                                    return $this->alipay($data);
                                } else {
                                    $arr = array('code' => 90011, 'message' => '该商户未开通支付宝支付通道');
                                    return json_encode($arr);
                                }
                            } elseif ($kt >= 10 && $kt <= 15) {
                                if ($machinfos['sub_mch_id'] !== '') {
                                    $pays['pay_fs'] = 2;
                                    $Paylog->save($pays);
                                    return $this->pay($data);
                                } else {
                                    $arr = array('code' => 90011, 'message' => '该商户未开通微信支付通道');
                                    return json_encode($arr);
                                }

                            } else {
                                $arr = array('code' => 90009, 'message' => '条码格式错误');
                                return json_encode($arr);
                            }
                            break;
                        case '1':
                            $Paylog->save($pays);
                            return $this->mspay($data);
                            break;

                    }


                } else {
                    $arr = array('code' => 90010, 'message' => '订单编号已存在');
                    return json_encode($arr);
                }
            } else {
                $arr = array('code' => 90008, 'message' => '请输入正确的金额');
                return json_encode($arr);
            }
        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
            return json_encode($arr);
        }
    }

    public function getcheckpay($data)
    {
        try {

            if (!empty($data['orderid'])) {
                $map['orderid'] = $data['orderid'];
            } elseif (!empty($data['orderid2'])) {
                $map['orderid'] = $data['orderid2'];
            } elseif (!empty($data['wsy_orderid'])) {
                $map['wsy_orderid'] = $data['wsy_orderid'];;
            }


            $Paylog = new Paylog();
            $payinfo = $Paylog->where($map)->field('pay_fs,orderid')->find();
            if ($payinfo) {
                $User = new Merchant();
                $shtd = $User->where(array('id' => $data['merchid']))->value('shtd');
                switch ($shtd) {
                    case '0':

//                return $Paylog->getLastSql();
                        $data['orderid'] = $payinfo['orderid'];

                        switch ($payinfo['pay_fs']) {
                            case '0':
                                $arr = $this->checkpay($data);
                                break;
                            case '1':
                                $arr = $this->alicheckpay($data);
                                break;
                            case '2':
                                $arr = $this->checkpay($data);
                                break;
                            case '3':
                                $arr = $this->alicheckpay($data);
                                break;
                            case '8':
                                $arr = $this->checkpay($data);
                                break;
                        }
                        break;
                    case '1':
                        $arr = $this->mscheckpay($data);
                        break;
                }
            } else {
                $arr = array('code' => '9091', 'message' => '订单编号不存在');

            }
        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($arr, JSON_UNESCAPED_UNICODE);

    }

    private function getzk($data)
    {
        $cardinfo = $this->getcard($data);
        if ($cardinfo) {
            $cardmember = new CardMember();
            $cardus = $cardmember->where('card_id', $cardinfo['card_id'])->find();
            $zt = $cardus['is_zf_discount'];
            $dz = $cardus['is_dj_discount'];
            //有一开启
            if ($zt == 1 || $dz == 1) {
                //等级折扣
                if ($dz == 1) {
                    $datas = $this->rankzk($data);
                }
                //支付折扣
                if ($zt == 1) {
                    if ($cardus['discount'] == 0) {
                        return 1;
                    } else {
                        $datas = $cardus['discount'] / 100;
                    }
                }
                //如果都开启
                if ($zt == 1 && $dz == 1) {
                    if ($cardus['discount'] == 0) {
                        return 1;
                    } else {
                        $card = $cardus['discount'] / 100;
                        $rank = $this->rankzk($data);
                        //比较大小
                        if ($rank < $card) {
                            //等级折扣
                            $datas = $rank;
                        } else {
                            //会员卡折扣
                            $datas = $card;
                        }
                    }
                }
            } else {
                //没有
                $datas = 1;
            }

        } else {
            $datas = 1;
        }

        return $datas;

    }

    //等级折扣
    private function rankzk($data)
    {
        $cardinfo = $this->getcard($data);
        if ($cardinfo) {
            $cardmember = new CardMember();
            $cardus = $cardmember->where('card_id', $cardinfo['card_id'])->find();
            $dz = $cardus['is_dj_discount'];
            if ($dz == 1) {
                //有
                $Merchant = new Merchant();
                $top_mid = $Merchant->where('id', $data['merchid'])->value('top_mid');
                $midlist = $Merchant->where('top_mid', $top_mid)->field('id')->select();
                $map['id'] = $data['merchid'];
                $Merchant = new Merchant();
                $Agent = new Agent();
                $WxOpen = new WxOpen();
                $config = $Merchant->where($map)->find();
                $agent = $Agent->where(array('id' => $config['agent']))->find();
                $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                $options = array(
                    'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                    'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                    'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                );
                $sh = $data['merchid'];
                $weObj = new Wxobjopen($options);
                //会员卡支付
                $appid = $WxOpen->where('id', $config['wx_open_id'])->value('authorizer_appid');
                $sparam['appid'] = $users['authorizer_appid'];
                $sparam['sub_appid'] = $appid;
                $sparam['mch_id'] = $agent['partnerid'];
                $sparam['sub_mch_id'] = $config['sub_mch_id'];
                $sparam['auth_code'] = $data['auth_code'];
                $getpenid = $weObj->get_open_id($sparam);
                if ($getpenid['return_code'] !== "FAIL") {
                    $openid = $getpenid['sub_openid'];
                    $card_id = $cardinfo['card_id'];
                    $CardUserGet = new CardUserGet();
                    $userinfo = $CardUserGet->where(['card_id' => $card_id, 'openid' => $openid])->find();
                    $level = getlive($card_id, $userinfo['bonus']);
                    $CardRank = new CardRank();
                    $rankinfo = $CardRank->where(['card_id' => $card_id, 'live' => $level])->find();
                    if ($rankinfo['discount']) {
                        $res = $rankinfo['discount'] / 100;
                    } else {
                        $res = 1;
                    }
                } else {
                    $res = 1;
                }
            } else {
                $res = 1;
            }
        } else {
            $res = 1;
        }

        return $res;
    }


    //卡券抵扣
    /*
     * 订单 $data
     * 返回 带有实际支付金额 price , 该笔订单所使用的卡券 card_id /code , 卡券所抵扣的金额 gel_card_zk ,  的订单 $data
     */
    private function card_deducted($data)
    {
        $openid = $this->getsubopenid($data);
        if ($openid) {
            $Merchant = new Merchant();
            $top_mid = $Merchant->where('id', $data['merchid'])->value('top_mid');
            $midlist = $Merchant->where('top_mid', $top_mid)->field('id')->select();
            //筛选符合条件的卡券
            foreach ($midlist as $k => $v) {
                $mid[] = $v['id'];
            }
            $mlist = implode(',', $mid);
            $map['mid'] = ['in', $mlist];
            $map['openid'] = $openid;
            $map['statu'] = ['neq', 2];
            $map['card_type'] = ['in', ['CASH', 'DISCOUNT']];
            $map['have'] = 1;
            $map['end_time'] = ['gt',time()];
            $CardUserGet = new CardUserGet();
            $cardli = $CardUserGet->where($map)->select();
            //判断是否有符合条件的卡券
            if ($cardli) {
                $should = $data['price'];           //应付
                foreach ($cardli as $k => $v) {
                    if (filteroffcard($v['card_id']) == true && filtercarddedu($v['card_id']) == true) {
                        $cardlist[$k] = $v;
                    } else {
                        $cardlist = [];
                    }
                }
                if (!empty($cardlist)) {
                    //使用最先领取的一张
                    foreach ($cardlist as $k => $v) {
                        //折扣券
                        if ($v['card_type'] == 'DISCOUNT') {
                            if (isset($card_id)) {
                                if (filtercarddedupile($v['card_id']) == false || $v['card_id'] == $card_id) {      //在已产生抵扣时判断是否支持叠加 / 本次循环card_id是否和上一次循环card_id相同
                                    continue;
                                }
                            }
                            $discount = getcardgeldis($v['card_id']) / 100;
                            $data['price'] = $discount * $data['price'];
                            $data1['hx_card'][$k]['card_id'] = $v['card_id'];
                            $data1['hx_card'][$k]['code'] = $v['code'];
                            if (filtercarddedupile($v['card_id']) == false) {
                                break;
                            } else {
                                $card_id = $v['card_id'];
                            }
                        } elseif ($v['card_type'] == 'CASH') {
                            //代金券
                            $cost = getcardgelcash($v['card_id']);              //获取代金券抵扣
                            if ($data['price'] >= $cost['least_cost']) {
                                if ($data['price'] - $cost['reduce_cost'] >= 0.01) {     //抵用后金额是否可支付
                                    if (isset($card_id)) {
                                        if (filtercarddedupile($card_id) == false || $v['card_id'] == $card_id) {        //在已产生抵扣时判断是否支持叠加 / 本次循环card_id是否和上一次循环card_id相同
                                            continue;
                                        }
                                    }
                                    $data['price'] = $data['price'] - $cost['reduce_cost'];
                                    $data1['hx_card'][$k]['card_id'] = $v['card_id'];
                                    $data1['hx_card'][$k]['code'] = $v['code'];
                                    if (filtercarddedupile($v['card_id']) == false) {        //判断是否可叠加
                                        break;
                                    } else {
                                        $card_id = $v['card_id'];
                                    }
                                }
                            }
                        }
                    }
                    //排列要核销的卡券
                    if (isset($data1['hx_card'])) {
                        $data1['hx_card'] = array_values($data1['hx_card']);
                        //返回数据
                        $data['hx_card'] = $data1['hx_card'];
                        $data['gel_card_zk'] = $should - $data['price'];
                    } else {
                        //返回数据
                        $data['hx_card'] = '0000';
                        $data['gel_card_zk'] = 0;
                    }

                    //卡券折扣
                    $data2['gel_card_zk'] = $should - $data['price'];
                    $data2['hx_card'] = json_encode($data['hx_card'], JSON_UNESCAPED_UNICODE);
                    //存入订单
                    $Paylog = new Paylog();
                    $Paylog->save($data2, ['orderid' => $data['orderid']]);

                    return $data;
                } else {
                    $data['hx_card'] = '0000';
                    $data['gel_card_zk'] = 0;
                    return $data;
                }
            } else {
                $data['hx_card'] = '0000';
                $data['gel_card_zk'] = 0;
                return $data;
            }
        } else {
            $data['hx_card'] = '0000';
            $data['gel_card_zk'] = 0;
            return $data;
        }

    }

    //核销执行
    /*
     *  订单记录中所使用的卡券 hx_card
     *  执行核销，将核销的卡券状态修改为2
     *  要核销的卡券为空时返回9009
     *  核销失败时返回9009
     *
     */
    private function pay_hx_card($arr, $data)
    {
        $CardUserGet = new CardUserGet();
        $CardConsume = new CardConsume();
        $Paylog = new Paylog();
        if (isset($arr) && is_array($arr)) {
//            $openid = $this->getsubopenid($data);
            foreach ($arr as $k => $v) {
                $options = $this->options($v['card_id']);
                $wxObj = new Wxobjopen($options);
                $res[$k] = $wxObj->consumeCode($v);
//                return $res;
                if (isset($res[$k]['errcode']) && $res[$k]['errcode'] == 0) {
                    $CardUserGet->save(['statu' => 2], $v);
                    //核销记录
                    $conlog[$k]['card_id'] = $v['card_id'];
                    $conlog[$k]['code'] = $v['code'];
                    $conlog[$k]['card_type'] = get_cardid_type_lden($v['card_id']);
                    $conlog[$k]['openid'] = $this->getcardopenid($v);
                    $conlog[$k]['mid'] = $data['merchid'];
                    $conlog[$k]['hx_fs'] = '消费抵扣';
                    $conlog[$k]['con_username'] = $data['cashier'];
                    $conlog[$k]['create_time'] = time();
                    $resu = '0000';
                } else {
                    $resu = '9009';
                }
            }
            if (isset($conlog)) {
                $CardConsume->allowField(true)->saveAll($conlog);
            }
            $pdata['hx_card_res'] = json_encode($res, JSON_UNESCAPED_UNICODE);
            if ($resu == '0000') {
                $pdata['hx_card_statu'] = 1;
            }
            $Paylog->allowField(true)->save($pdata, ['orderid' => $data['orderid']]);
            $resu = $pdata['hx_card_res'];
        } else {
            $resu = '9009';
        }
        return $resu;
    }

    //获取cardopenid
    private function getcardopenid($arr)
    {
        $CardUserGet = new CardUserGet();
        $openid = $CardUserGet->where($arr)->value('openid');
        if ($openid) {
            return $openid;
        } else {
            return 0;
        }
    }

    //获取subopenid
    private function getsubopenid($data)
    {
//        return json_encode($data);
        $Merchant = new Merchant();
//        $top_mid = $Merchant->where('id', $data['merchid'])->value('top_mid');
        $map['id'] = $data['merchid'];
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);
        //会员卡支付
        $appid = $WxOpen->where('id', $config['wx_open_id'])->value('authorizer_appid');
        $sparam['appid'] = $users['authorizer_appid'];
        $sparam['sub_appid'] = $appid;
        $sparam['mch_id'] = $agent['partnerid'];
        $sparam['sub_mch_id'] = $config['sub_mch_id'];
        $sparam['auth_code'] = $data['auth_code'];
        $getpenid = $weObj->get_open_id($sparam);
        if ($getpenid['return_code'] !== "FAIL" && $getpenid['result_code'] !== "FAIL") {
            $openid = $getpenid['sub_openid'];
        } else {
            $openid = '';
        }
        return $openid;
    }

    //获取会员卡信息
    private function getcard($data)
    {

        $Merchant = new Merchant();
        $top_mid = $Merchant->where('id', $data['merchid'])->value('top_mid');
        $midlist = $Merchant->where('top_mid', $top_mid)->field('id')->select();

        $map['id'] = $data['merchid'];
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );

        $sh = $data['merchid'];
        $weObj = new Wxobjopen($options);
        //会员卡支付
        $appid = $WxOpen->where('id', $config['wx_open_id'])->value('authorizer_appid');

        $sparam['appid'] = $users['authorizer_appid'];
        $sparam['sub_appid'] = $appid;
        $sparam['mch_id'] = $agent['partnerid'];
        $sparam['sub_mch_id'] = $config['sub_mch_id'];
        $sparam['auth_code'] = $data['auth_code'];
        $getpenid = $weObj->get_open_id($sparam);

        if ($getpenid['return_code'] !== "FAIL" && $getpenid['result_code'] !== "FAIL") {
            $openid = $getpenid['sub_openid'];
            $CardUserGet = new CardUserGet();
            $top_mid = $Merchant->where('id', $sh)->value('top_mid');
            $smid = [];
            $midlist = $Merchant->where('top_mid', $top_mid)->field('id')->select();
            foreach ($midlist as $k => $v) {
                $smid[] = $v['id'];
            }
            $mid = implode(',', $smid);
            $me['openid'] = $openid;
            $me['mid'] = array('in', $mid);
            $me['have'] = 1;
            $me['statu'] = 0;
            $me['fire'] = 1;
            $me['card_type'] = 'MEMBER_CARD';
            $cardinfo = $CardUserGet->where($me)->find();

        } else {
            $cardinfo = [];
        }
        return $cardinfo;
    }

    public function card_pay($data)
    {
        //会员卡支付

        if ($data['confirm'] == "no") {
            //判断是否为0
            if ($data['price'] <> 0) {
                $Merchant = new Merchant();
                $top_mid = $Merchant->where('id', $data['merchid'])->value('top_mid');
                $midlist = $Merchant->where('top_mid', $top_mid)->field('id')->select();
                $map['id'] = $data['merchid'];
                $Merchant = new Merchant();
                $Agent = new Agent();
                $WxOpen = new WxOpen();
                $config = $Merchant->where($map)->find();
                $agent = $Agent->where(array('id' => $config['agent']))->find();
                $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                $options = array(
                    'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                    'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                    'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                );
                $sh = $data['merchid'];
                $weObj = new Wxobjopen($options);
                //会员卡支付
                $appid = $WxOpen->where('id', $config['wx_open_id'])->value('authorizer_appid');
                $sparam['appid'] = $users['authorizer_appid'];
                $sparam['sub_appid'] = $appid;
                $sparam['mch_id'] = $agent['partnerid'];
                $sparam['sub_mch_id'] = $config['sub_mch_id'];
                $sparam['auth_code'] = $data['auth_code'];
                $getpenid = $weObj->get_open_id($sparam);
                if ($getpenid['return_code'] == "SUCCESS") {
                    if ($getpenid['result_code'] == "SUCCESS") {
                        $openid = $getpenid['sub_openid'];
                        $CardUserGet = new CardUserGet();
                        $top_mid = $Merchant->where('id', $sh)->value('top_mid');
                        $midlist = $Merchant->where('top_mid', $top_mid)->field('id')->select();
                        $smid = [];
                        foreach ($midlist as $k => $v) {
                            $smid[] = $v['id'];
                        }
                        $mid = implode(',', $smid);
                        $me['openid'] = $openid;
                        $me['mid'] = array('in', $mid);
                        $me['have'] = 1;
                        $me['statu'] = 0;
                        $me['fire'] = 1;
                        $me['card_type'] = 'MEMBER_CARD';

                        $cardinfos = $CardUserGet->where($me)->find();

                        if ($cardinfos) {
                            if ($data['price'] <= $cardinfos['balance']) {
                                //判断赠送金额是否为0
                                if ($cardinfos['cs_balance'] <> 0) {
                                    //判断赠送金额是否超过核销金额
                                    if ($cardinfos['cs_balance'] < $data['price']) {
                                        //赠送金额归0
                                        $CardUserGet->where($map)->setField('cs_balance', 0);
                                    }
                                    //更新赠送金额
                                    $CardUserGet->where($map)->setDec('cs_balance', $data['price']);
                                }
                                //应付
//                            $yf_price = $data['price'];
                                //判断是否折扣
                                $CardMember = new CardMember();
                                $card = $CardMember->where('card_id', $cardinfos['card_id'])->find();
                                if ($card['is_cz_discount'] == 1) {
                                    $pay_balance = $data['price'];
                                    $discount = $card['discount'] / 100;
                                    if ($discount == 0) {
                                        $data['price'] = $data['price'];
                                    } else {

                                        $data['price'] = $data['price'] * $discount;

                                    }
                                } else {
                                    $pay_balance = $data['price'];
                                }
                                //卡券抵扣
                                $dedu_res = $this->card_deducted($data);
                                $data['price'] = $dedu_res['price'];
                                $CardUserGet->where(array('card_id' => $cardinfos['card_id'], 'code' => $cardinfos['code']))->setDec('balance', $data['price']);
                                if ($dedu_res['hx_card'] <> '0000') {
                                    $this->pay_hx_card($dedu_res['hx_card'], $data);
                                }
                                //END
                                $datas2['mid'] = $sh;
                                $datas2['openid'] = $openid;
                                $datas2['code'] = $cardinfos['code'];
                                $datas2['card_id'] = $cardinfos['card_id'];
                                $datas2['create_time'] = time();
                                $datas2['outerid'] = $sh;
                                $datas2['record_balance'] = '消费';
//                            $datas2['type'] = 2;
                                $datas2['hx_fs'] = 8;
                                $datas2['type'] = 2;
                                $datas2['cate'] = 2;
                                $datas2['reason'] = 19;
                                $datas2['source'] = 9;
                                $datas2['con_username'] = $data['cashier'];
//                            $datas2['hx_fs'] = '客户端';
                                $datas2['del_balance'] = $data['price'];
                                $datas2['pay_balance'] = $pay_balance;
//                                $Wxuserupdate = new CardUserUpdate();
//                                $result = $Wxuserupdate->allowField(true)->save($datas2);
                                $pays['orderno'] = 1000000000000;
                                $pays['pay_time'] = date('YmdHis');
                                $pays['pay_statu'] = 1;
                                $pays['openid'] = $openid;
                                $pays['payinfo'] = "会员卡支付";
                                $pays['price'] = $data['price'];
                                $pays['pay_fs'] = 8;
                                $pays['yf_price'] = $pay_balance;
                                $spa['card_id'] = $cardinfos['card_id'];
                                $spa['openid'] = $cardinfos['openid'];
                                $spa['add_balance'] = $data['price'];
                                $spa['balance'] = $CardUserGet->where(['id' => $cardinfos['id']])->value('balance');
                                $spa['pay_balance'] = 0;
                                $spa['type'] = 2;
//                            file_put_contents('/data2/html/payos/1556.txt', json_encode($data), 8);
                                $wxMesg = new Wxtplmesg();
                                $res = $wxMesg->balancesendmesg($spa);
                                $Paylog = new Paylog();
                                $Paylog->save($pays, ['orderid' => $data['orderid']]);
                                $data2['orderid'] = $data['orderid'];
                                $data2['id'] = $data['merchid'];
                                $data2['zk_price'] = 0;
                                $data2['yf_price'] = $pay_balance;
//                                file_put_contents('/data2/html/payos/1557.txt', json_encode($data), 8);


                                $data2['type'] = 'pay';
                                $data2['pay_fs'] = 8;
                                $data2['pay_time'] = date('YmdHis');
                                $data2['outTradeNo'] = $data['outTradeNo'];
                                $data2['transaction_id'] = "";
                                $data2['pay_fs'] = 8;
                                $data2['code'] = 0;
                                $data2['message'] = "success";
//                                file_put_contents('/data2/html/payos/1556.txt', json_encode($data2), 8);

                                $Paylog = new Paylog();
                                $payinfo = $Paylog->where(['orderid' => $data['orderid']])->find();
                                $data2['price'] = $payinfo['price'];
                                $data2['ought_price'] = $payinfo['yf_price'];//应付
                                $data2['dis_card_zk'] = $payinfo['dis_card_zk'];        //会员卡折扣     field('dis_card_zk,vip_card_zk,gel_card_zk,hx_card')->
                                $data2['vip_card_zk'] = $payinfo['vip_card_zk'];        //等级折扣
                                $data2['gel_card_zk'] = $payinfo['gel_card_zk'];        //卡券抵扣
                                $data2['dedu_zk_info'] = getdeduzkinfo($payinfo['hx_card'],$payinfo['gel_card_zk']).getdiszkinfo($payinfo['dis_card_zk']).getvipzkinfo($payinfo['vip_card_zk']);        //抵扣明细
                            } else {
                                $data2=$data;
                                $data2['code'] = 9098;
                                $data2['message'] = "会员卡余额不足";
                            }
                            return $data2;
                        }
                    }
                } else {

                    $data2['code'] = 9004;
                    $data2['message'] = $getpenid['err_code_des'];
                }
            } else {
                $data2['code'] = 9003;
                $data2['message'] = "请输入正确的支付金额";
                return $data2;
            }

        }

    }


    //积分更新
    public function updatebonus($arr)
    {

        //实例化微信
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $data = [
            'code' => $arr['code'],
            'card_id' => $arr['card_id'],
            'record_bonus' => $arr['record_bonus'],
            'add_bonus' => $arr['add_bonus'],
            'notify_optional' => [
                'is_notify_bonus' => true,
                'is_notify_balance' => true,
                'is_notify_custom_field1' => true,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }


    public function pay($data)
    {
        try {
            $s = $this->card_pay($data);
            if ($s == '' || $s == null) {
                $map['id'] = $data['merchid'];
                $Merchant = new Merchant();
                $Agent = new Agent();
                $WxOpen = new WxOpen();
                $config = $Merchant->where($map)->find();
                $agent = $Agent->where(array('id' => $config['agent']))->find();
                $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
                $options = array(
                    'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                    'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                    'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                );
                $sh = $data['merchid'];
                $weObj = new Wxobjopen($options);
                //会员卡支付
                if (isset($data['fs']) && $data['fs'] == "cz") {
                    $zk = 1;
                } else {
                    $zk = $this->getzk($data);
                }
                $price1 = $data['price'] * $zk;
                $card_price = $price1;
                //会员卡折扣
                $paylogdata['dis_card_zk'] = $data['price'] - $price1;
                $Paylog = new Paylog();
                $Paylog->allowField(true)->save($paylogdata,array('orderid'=>$data['orderid']));
                //卡券抵扣
                $data3 = $data;
                $data3['price'] = $price1;
                $dedu_res = $this->card_deducted($data3);       //抵扣返回
                $price2 = $dedu_res['price'];                    //实际支付
                //END
                //支付金额保留两位小数
                $price = fmt_price($price2);
                //END
                $appid = $users['authorizer_appid'];
                $mch_id = $agent['partnerid'];
                $out_trade_no = $data['orderid'];
                $body = "快捷支付";
                $sub_mch_id = $config['sub_mch_id'];
                if ($zk !== 1) {
                    $Paylog = new Paylog();
                    $ssdata['zk_price'] = $data['price'] - $price;
                    $Paylog->save($ssdata, ['orderid' => $out_trade_no]);
                }
                if ($userwx['authorizer_appid'] !== $appid) {
                    $sub_appid = $userwx['authorizer_appid'];
                } else {
                    $sub_appid = '';
                }
                $total_fee = $price * 100;
                $spbill_create_ip = $data['client_ip'];
                $nonce_str = $weObj->generateNonceStr();
                $auth_code = $data['auth_code'];
                $pay_xml = $weObj->createmicroPackageXml($appid, $sub_appid, $mch_id, $out_trade_no, $body, $sub_mch_id, $total_fee, $spbill_create_ip, $nonce_str, $auth_code);
                $pay_xml = $weObj->Mircopay_post($pay_xml);
                $data2 = $this->payzt($pay_xml, $sh, $out_trade_no);

                $data2['zk_price'] = $data['price'] - $card_price;  //会员卡折扣
                $data2['yf_price'] = $data['price'];                //应付

//                $data2['gel_card_zk'] = $data['price'] - $price;    //卡券折扣

                $data2['price'] = $price;

                $data2['orderid'] = $out_trade_no;
                $data2['outTradeNo'] = $data['outTradeNo'];
                $data2['id'] = $data['merchid'];
                $data2['type'] = 'pay';
                $data2['pay_fs'] = 2;

            } else {
                $data2 = $s;
            }
        } catch (\Exception $e) {
            $data2 = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($data2);
    }

    public function payzt($pay_xml, $id, $orderid)
    {

        try {
            if ($pay_xml['return_code'] == "SUCCESS") {

                if ($pay_xml['result_code'] == "FAIL") {

//
                    switch ($pay_xml['err_code']) {
                        case 'USERPAYING':
                            $error_code = 21001;
                            break;
                        case "ORDERPAID":
                            $error_code = 21002;
                            break;
                        default:
                            $error_code = $pay_xml['err_code'];
                            break;
                    }
                    $data['code'] = $error_code;
                    $data['message'] = $pay_xml['err_code'];

                } else {
                    if ($pay_xml['return_code'] && $pay_xml['result_code'] != "SUCCESS") {

                        $data['message'] = $pay_xml['err_code_des'];
                        $data['code'] = $pay_xml['err_code'];
                    } elseif (isset($pay_xml['trade_state']) && $pay_xml['trade_state'] != "SUCCESS") {
                        $data['message'] = $pay_xml['trade_state'];
                        $data['code'] = $pay_xml['trade_state'];
                    } else {
                        $Paylog = new Paylog();
                        $data['code'] = 0;
                        $data['message'] = "success";
                        $data['transaction_id'] = $pay_xml['transaction_id'];
                        $data['pay_time'] = $pay_xml['time_end'];


                        //END
                        $pays['orderno'] = $pay_xml['transaction_id'];
                        $pays['pay_time'] = $pay_xml['time_end'];
                        $pays['pay_statu'] = 1;
                        $pays['openid'] = $pay_xml['openid'];
                        $pays['payinfo'] = json_encode($pay_xml);
                        $pays['price'] = $pay_xml['total_fee'] / 100;
                        if (isset($pay_xml['total_fee'])) {
                            $pays['price'] = $pay_xml['total_fee'] / 100;           //标价金额
                        }
                        if (isset($pay_xml['coupon_fee'])) {
                            $pays['coupon_fee'] = $pay_xml['coupon_fee'] / 100;     //折扣金额
                        }
                        if (isset($pay_xml['cash_fee'])) {
                            $pays['cash_fee'] = $pay_xml['cash_fee'] / 100;         //支付金额
                        }

                        //卡券核销
                        $gel_card_zk = $Paylog->where(['orderid' => $orderid])->value('gel_card_zk');
                        if (isset($gel_card_zk) && $gel_card_zk > 0) {
                            $hx_card_statu = $Paylog->where(['orderid' => $orderid])->value('hx_card_statu');
                            if ($hx_card_statu == 0) {
                                $hx_card = $Paylog->where(['orderid' => $orderid])->value('hx_card');
                                $hx_card1 = json_decode($hx_card, true);
                                $hx_data['merchid'] = $Paylog->where(['orderid' => $orderid])->value('mid');
                                $hx_data['cashier'] = $Paylog->where(['orderid' => $orderid])->value('cashier');
                                $hx_data['orderid'] = $orderid;
                                $hx_card_res = $this->pay_hx_card($hx_card1, $hx_data);
                            }
//                            //信息更新
//                            $pays['gel_card_zk'] = $hx_card['gel_card_zk'];      //卡券抵扣
//                            $pays['hx_card'] = json_encode($hx_card,JSON_UNESCAPED_UNICODE);
//                            $pays['hx_card_res'] = json_encode($hx_card_res,JSON_UNESCAPED_UNICODE);
                        }
                        //end
                        $Paylog->save($pays, ['orderid' => $orderid]);
                        if (isset($pay_xml['sub_openid'])) {
                            $barr['openid'] = $pay_xml['sub_openid'];
                        } else {
                            $barr['openid'] = $pay_xml['openid'];
                        }

                        $barr['price'] = $pay_xml['total_fee'] / 100;

                        $this->bonusgive($barr);
                        action('index/wxauth/sendtemplate', array($id, $orderid));
//

                    }

                }
            } elseif ($pay_xml['return_code'] == "FAIL") {

                $data['info'] = $pay_xml['return_msg'];
            }

        } catch (\Exception $e) {

            $data = array('code' => '9099', 'message' => '系统错误');
        }
        $Paylog = new Paylog();
        $payinfo = $Paylog->where(['orderid' => $orderid])->find();
        $data['ought_price'] = $payinfo['yf_price'];//应付
        $data['dis_card_zk'] = $payinfo['dis_card_zk'];        //会员卡折扣     field('dis_card_zk,vip_card_zk,gel_card_zk,hx_card')->
        $data['vip_card_zk'] = $payinfo['vip_card_zk'];        //等级折扣
        $data['gel_card_zk'] = $payinfo['gel_card_zk'];        //卡券抵扣
        $data['dedu_zk_info'] = getdeduzkinfo($payinfo['hx_card'],$payinfo['gel_card_zk']).getdiszkinfo($payinfo['dis_card_zk']).getvipzkinfo($payinfo['vip_card_zk']);        //抵扣明细
        return $data;


    }

    /*
    * 积分规则
    * price（变动说明）openid（用户会员卡编号）
    * //需要card_id(会员卡ID)，add_bonus(变动积分)，record_bonus（变动说明）code（用户会员卡编号）
    */
    public function bonusgive($arr)
    {
        $CardMember = new CardMember();
        $CardUserGet = new CardUserGet();
        $map['openid'] = $arr['openid'];
        $map['card_type'] = 'MEMBER_CARD';
        $user = $CardUserGet->where($map)->find();
        //判断是否会员
        if ($user) {
            $card = $CardMember->where('card_id', $user['card_id'])->find();
            if ($card['supply_bonus'] == 1) {
                //设置积分
                $bonus_rule = json_decode($card['bonus_rule'], true);
                //比例和积分
                $bili = @($bonus_rule['increase_bonus'] / $bonus_rule['cost_money_unit']);
                $add_bonus = floor($arr['price'] * $bili);
                //同步微信数据
//                if($arr['fs'] == 'cz'){
//                    $arr['record_bonus'] = '充值赠送';
//                }else{
                $arr['record_bonus'] = '支付赠送';
//                }
                $CardBonusRule = new CardBonusRule();
                //禁止规则
                $mar['end_time'] = ['egt', time()];
                $mar['card_id'] = $user['card_id'];
                $mar['type'] = 1;
                $mar['statu'] = 0;
                $ruledis = $CardBonusRule->where($mar)->find();
                if (empty($ruledis)) {
                    //多倍规则
                    $mab['end_time'] = ['egt', time()];
                    $mab['card_id'] = $user['card_id'];
                    $mab['type'] = 2;
                    $mab['statu'] = 0;
                    $rulemax = $CardBonusRule->where($mab)->find();
                    //多倍积分
                    if ($rulemax) {
                        $CardUserGet = new CardUserGet();
                        $barr['add_bonus'] = $add_bonus * $rulemax['bonus_max'];               //积分变动
                        $barr['card_id'] = $user['card_id'];                                         //卡券ID
                        $barr['code'] = $user['code'];                                               //卡券CODE
                        $barr['record_bonus'] = $arr['record_bonus'];                               //说明
                        $res = $this->updatebonus($barr);
                        if ($res['errcode'] == 0) {
                            $mad['card_id'] = $user['card_id'];
                            $mad['code'] = $user['code'];
                            $CardUserGet->where($mad)->setField('bonus', $res['result_bonus']);
                            $datas = $res;
                        } else {
                            $datas = ['msg' => $res['errmsg'], 'code' => '9002'];
                        }
                        //普通积分
                    } else {
                        $CardUserGet = new CardUserGet();
                        $barr['add_bonus'] = $add_bonus;               //积分变动
                        $barr['card_id'] = $user['card_id'];                                         //卡券ID
                        $barr['code'] = $user['code'];                                               //卡券CODE
                        $barr['record_bonus'] = $arr['record_bonus'];                               //说明
                        $res = $this->updatebonus($barr);
                        if ($res['errcode'] == 0) {
                            $mad['card_id'] = $user['card_id'];
                            $mad['code'] = $user['code'];
                            $CardUserGet->where($mad)->setField('bonus', $res['result_bonus']);
                            $datas = $res;
                        } else {
                            $datas = ['msg' => $res['errmsg'], 'code' => '9002'];
                        }
                    }
                    //保存更新记录
                    $datas['mid'] = $card['mid'];
                    $datas['openid'] = $user['openid'];
                    $datas['code'] = $user['code'];
                    $datas['card_id'] = $user['card_id'];
                    $datas['create_time'] = time();
                    $datas['outerid'] = $card['mid'];
                    $datas['hx_fs'] = 4;
                    $datas['type'] = 6;                                   //类别
                    $datas['cate'] = 1;
                    $datas['reason'] = 1;
                    $datas['source'] = 9;
                    $datas['add_bonus'] = $barr['add_bonus'];
                    $datas['record_bonus'] = $barr['record_bonus'];
                    $Wxuserupdate = new CardUserUpdate();
                    $Wxuserupdate->allowField(true)->save($datas);
                } else {
                    $datas = ['msg' => '该时间段内不可积分', 'code' => '9004'];
                }
            } else {
                $datas = [];
            }
        } else {
            $datas = ['msg' => '无该会员', 'code' => '9005'];
        }
        return $datas;
    }


    public function checkpay($data)
    {
        try {
            $orderid = $data['orderid'];

            $id = $data['merchid'];
            $payxml = $this->orderquery($id, $orderid);
//            return $payxml;

            $data2 = $this->payzt($payxml, $id, $orderid);

            $data2['orderid'] = $orderid;
            $data2['id'] = $id;
            $Paylog = new Paylog();
            $payinfo = $Paylog->where(array('orderid' => $orderid))->find();
//            $data2['zk_price'] = $payinfo['zk_price'];
//            $data2['dis_card_zk'] = $payinfo['dis_card_zk'];        //会员卡折扣
//            $data2['vip_card_zk'] = $payinfo['vip_card_zk'];        //等级折扣
//            $data2['gel_card_zk'] = $payinfo['gel_card_zk'];        //卡券抵扣
//
//            $data2['dedu_zk_info'] = getdeduzkinfo($payinfo['hx_card'],$payinfo['gel_card_zk']).getdiszkinfo($payinfo['dis_card_zk']).getvipzkinfo($payinfo['vip_card_zk']);        //抵扣明细
            $data2['zk_price'] = $payinfo['zk_price'];
            $data2['wsy_orderid'] = $payinfo['wsy_orderid'];
//            $data2['outTradeNo'] = $payinfo['wsy_orderid'];
            $data2['yf_price'] = $payinfo['zk_price'] + $payinfo['price'];
            $data2['price'] = $payinfo['price'];
            $data2['type'] = 'checkpay';
            $data2['pay_fs'] = 2;
        } catch (\Exception $e) {
            $data2 = array('code' => '9099', 'message' => '系统错误');
        }

        return $data2;


    }

    public function orderquery($id, $orderid)
    {

        try {
            $map['id'] = $id;
            $config = Db::name('Merchant')->where($map)->find();
            $agent = Db::name('agent')->where(array('id' => $config['agent']))->find();
            $users = Db::name('wx_open')->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = Db::name('wx_open')->where(array('id' => $config['wx_open_id']))->find();

            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );

            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $orderid;
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $nonce_str = $weObj->generateNonceStr();
            $array = array('id' => $id, 'orderid' => $orderid, 'appid' => $appid, 'mch_id' => $mch_id, 'out_trade_no' => $out_trade_no, 'sub_mch_id' => $sub_mch_id, 'nonce_str' => $nonce_str);

            $orderxml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
//return $orderxml;
            $orderxml2 = $weObj->getPayNum($orderxml);

        } catch (\Exception $e) {
            $orderxml2 = array('code' => '9099', 'message' => '系统错误');
        }
        return $orderxml2;

    }

    public function alipay($data)
    {
        try {

            $User = new Merchant();
            $Agent = new Agent();

            $users = $User->where(array('id' => $data['merchid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();

            $options = array(

                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],

            );
            $aliObj = new Alipayobj($options);
            $price = $data['price'];
            $sh = $data['merchid'];
            $out_trade_no = $data['orderid'];
            $body = "快捷支付";
            $auth_code = $data['auth_code'];
            $total_fee = $price;
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.trade.pay";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['notify_url'] = 'https://' . $agent['open_url'];
            $data['app_auth_token'] = $users['ali_merid'];
            $biz_content['out_trade_no'] = $out_trade_no;
            $biz_content['scene'] = 'bar_code';
            $biz_content['auth_code'] = $auth_code;
            $biz_content['total_amount'] = $total_fee;
            $biz_content['subject'] = $body;
            $biz_content['alipay_store_id'] = $users['ali_store_id'];

            if ($data['merchid'] == 502) {
                $biz_content['enable_pay_channels'] = 'pcreditpayInstallment';
                $extend_params['hb_fq_num'] = 12;
                $extend_params['hb_fq_seller_percent'] = 0;
            }
            $extend_params['sys_service_provider_id'] = $agent['sys_service_provider_id'];
            $biz_content['extend_params'] = $extend_params;
            $data['biz_content'] = json_encode($biz_content);

//            $data['biz_content'] = json_encode(array(
//                'out_trade_no' => $out_trade_no,
//              //  'enable_pay_channels'=>,
//                'scene' => 'bar_code',
//                'auth_code' => $auth_code,
//                'total_amount' => $total_fee,
//                'subject' => $body,
//                'alipay_store_id' => $users['ali_store_id'],
////                'store_id'=>I('get.id'),
//                'extend_params' => array(
//                    'sys_service_provider_id' => $agent['sys_service_provider_id'],
////                    'hb_fq_num'=>'3',
////                    'hb_fq_seller_percent'=>100,
//                ),
//
//            ));
//      $sss=$aliObj->getSignContent($data);
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            $sj = $aliObj->scanpay($data);
            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
            $data2 = $this->alipayzt($content['alipay_trade_pay_response'], $sh, $out_trade_no);
            $data2['zk_price'] = $data['price'] - $price;
            $data2['yf_price'] = $data['price'];
            $data2['price'] = $price;
            $data2['orderid'] = $out_trade_no;
            $data2['outTradeNo'] = $data['outTradeNo'];
            $data2['id'] = $data['merchid'];
            $data2['type'] = 'pay';
            $data2['pay_fs'] = 3;
        } catch (\Exception $e) {
            $data2 = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($data2);


    }

    public function alipayzt($contents, $sh, $orderid, $fs = '')
    {

        try {
            if ($fs == "checkpay") {

                if ($contents['code'] == 10000) {
                    switch ($contents['trade_status']) {
                        case 'WAIT_BUYER_PAY':
                            $data['code'] = $contents['code'];
                            $data['message'] = "USERPAYING";
                            break;
                        case 'TRADE_CLOSED':
                            $data['code'] = $contents['code'];
                            $data['message'] = "NOTPAY";//订单超时已关闭
                            break;
                        case 'TRADE_FINISHED':
                            $data['code'] = $contents['code'];
                            $data['message'] = "errro";//交易结束不可退款
                            break;
                        case 'TRADE_SUCCESS':
                            $pays['pay_statu'] = 1;
                            $pays['orderno'] = $contents['trade_no'];
                            if (isset($contents['gmt_payment'])) {
                                $pay_time = date('YmdHis',strtotime($contents['gmt_payment']));;
                            } elseif (isset($contents['send_pay_date'])) {
                                $pay_time =  date('YmdHis',strtotime($contents['send_pay_date']));;
                            } else {
                                $pay_time = "";
                            }
                            $pays['pay_time'] = $pay_time;
                            $pays['price'] = $contents['total_amount'];
                            $pays['payinfo'] = json_encode($contents);
                            $Paylog = new Paylog();
                            $Paylog->save($pays, ['orderid' => $orderid]);
                            $data['code'] = 0;
                            $data['pay_time'] = $pay_time;
                            $data['message'] = "success";
                            $data['transaction_id'] = $contents['trade_no'];
                            action('index/wxauth/sendtemplate', array($sh, $orderid));
                            break;
                    }


                } else {
                    $data['code'] = $contents['code'];
                    $data['message'] = "error";
                }

            } else {
                if ($contents['code'] == 10000) {

                    if ($contents['msg'] = "Success") {

                        $data['code'] = 0;
                        $data['message'] = "success";
                        $data['pay_time'] = date('YmdHis',strtotime($contents['gmt_payment']));;
                        $data['transaction_id'] = $contents['trade_no'];
                        $pays['pay_statu'] = 1;
                        $pays['orderno'] = $contents['trade_no'];
                        $pays['pay_time'] =$contents['gmt_payment'];
                        $pays['price'] = $contents['total_amount'];
                        $pays['payinfo'] = json_encode($contents);
                        $Paylog = new Paylog();
                        $Paylog->save($pays, ['orderid' => $orderid]);

                    }
                } elseif ($contents['code'] == 10003) {
                    $data['code'] = $contents['code'];
                    $data['message'] = "USERPAYING";

                } elseif ($contents['code'] = 40004) {
                    $data['code'] = $contents['sub_code'];
                    $data['message'] = $contents['sub_msg'];

                }
            }
        } catch (\Exception $e) {
            $data = array('code' => '9099', 'message' => '系统错误');
        }
        $Paylog = new Paylog();
        $payinfo = $Paylog->where(array('orderid' => $orderid))->field('zk_price,yf_price,price')->find();
        $data['ought_price'] = $payinfo['yf_price'];//应付

        $data['zk_price'] = $payinfo['zk_price'];
        $data['dis_card_zk'] = 0;        //会员卡折扣
        $data['vip_card_zk'] = 0;        //等级折扣
        $data['gel_card_zk'] = 0;        //卡券抵扣

        $data['dedu_zk_info'] = '';        //抵扣明细
        return $data;
    }

    public function alicheckpay($data)
    {

        try {
            $orderid = $data['orderid'];
            $id = $data['merchid'];
            $payxml = $this->aliorderquery($id, $orderid);
            $data2 = $this->alipayzt($payxml['alipay_trade_query_response'], $id, $orderid, "checkpay");
            $Paylog = new Paylog();
            $payinfo = $Paylog->where(array('orderid' => $orderid))->find();
            $data2['wsy_orderid'] = $payinfo['wsy_orderid'];

            $data2['yf_price'] = $payinfo['zk_price'] + $payinfo['price'];
            $data2['price'] = $payinfo['price'];
            $data2['orderid'] = $orderid;
            $data2['id'] = $id;
            $data2['pay_fs'] = 3;
            $data2['type'] = 'checkpay';
        } catch (\Exception $e) {
            $data2 = array('code' => '9099', 'message' => '系统错误');
        }
        return $data2;


    }

    public function aliorderquery($id, $orderid)
    {

        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $id))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $out_trade_no = $orderid;
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.trade.query";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['notify_url'] = 'https://tp5.weilinzhou.com';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_trade_no' => $out_trade_no,
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $sj = $aliObj->scanpay($data);
        return $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);


    }

    public function mspay($data)
    {
//        $data['merchid']=724;
//        $data['auth_code']='131963756943230081';
//        $data['price']=0.01;
        try {
            $orderid = $data['orderid'];
            $map['id'] = $data['merchid'];
            $User = new Merchant();
            $Agent = new Agent();
            $config = $User->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();

            $options = array(
                'cmmb_key' => $agent['cmmb_key'],
            );
            $weObj = new Wxobjopen($options);

            $param['merNo'] = $config['cmmb_mer_id'];
            $param['authCode'] = $data['auth_code'];
            $param['orderNo'] = $orderid;
            $param['amount'] = $data['price'] * 100;
            $param['reqId'] = $orderid;
            $param['reqTime'] = date('YmdHis');
            $param['termNo'] = $data['merchid'];
            $param['goodsName'] = '快捷支付';
            $param['operatorId'] = '1';

            $param['signIn'] = $weObj->getcmmbpaysignature($param);

            $sj = $weObj->getcmmbscanpay($param);
            $sj = json_decode($sj, true);

            $data2 = $this->mspayzt($sj, $data['merchid'], $sj['orderNo'], "pay");

            $data2['orderid'] = $orderid;
            $data2['id'] = $data['merchid'];
            $data2['type'] = 'pay';

        } catch (\Exception $e) {
            $data2 = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($data2);

    }

    public function mspayzt($pay_xml, $id, $orderid, $sjfs)
    {

        try {

            switch ($pay_xml['result']) {
                case "0000":

                    $data['code'] = 0;
                    $data['message'] = "success";

                    $pays['orderno'] = $pay_xml['outOrderNo'];
                    $pays['pay_time'] = $pay_xml['payTime'];
                    $pays['pay_statu'] = 1;
                    $pays['openid'] = $pay_xml['uuid'];
                    if ($sjfs == "pay") {

                        $pays['ms_orderid'] = $pay_xml['transId'];
                    } else {
                        $pays['ms_orderid'] = $pay_xml['orgTransId'];
                    }
                    $pays['pay_fs'] = $this->getmspay_fs($pay_xml['channelFlag']);
                    $pays['payinfo'] = json_encode($pay_xml);
                    $Paylog = new Paylog();
                    $Paylog->save($pays, ['orderid' => $orderid]);
                    action('index/wxauth/sendtemplate', array($id, $orderid));

                    break;
                case "0042":
                    $data['code'] = 'USERPAYING';
                    $data['message'] = 'USERPAYING';
                    break;
                default:
                    $data['code'] = $pay_xml['result'];
                    $data['message'] = $pay_xml['desc'];
            }
        } catch (\Exception $e) {
            $data = array('code' => '9099', 'message' => '系统错误');
        }

        return $data;


    }

    public function getmspay_fs($fs)
    {
        switch ($fs) {
            case "00":
                $data = 2;
                break;
            case "01":
                $data = 3;
                break;
        }
        return $data;

    }

    public function msorderquery($id, $orderid)
    {
        $map['id'] = $id;
        $User = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $config = $User->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $options = array(
            'cmmb_key' => $agent['cmmb_key'],
        );

        $weObj = new Wxobjopen($options);
        $param['merNo'] = $config['cmmb_mer_id'];
        $param['orderNo'] = $orderid;
        $param['signIn'] = $weObj->getcmmbpaysignature($param);
        $sj = $weObj->getcmmborderquery($param);
        $sj = json_decode($sj, true);
        return $sj;
    }

    public function mscheckpay($data)
    {
        try {
            $orderid = $data['orderid'];

            $id = $data['merchid'];

            $payxml = $this->msorderquery($id, $orderid);
            $data2 = $this->mspayzt($payxml, $id, $orderid, "checkpay");
            $data2['orderid'] = $orderid;
            $data2['id'] = $id;
            $data2['type'] = 'checkpay';

        } catch (\Exception $e) {
            $data2 = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($data2);

    }

    private function getorder($sh)
    {

        $order = "H" . $sh  . date('YmdHis') . rand(10000, 99999) . rand(1, 9);
//        Session::set('orderid', $order);
        return $order;

    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //取支付额
    private function format_price($price)
    {
        $price = (float)$price;//将数值转换为浮点数
        $str = explode(".", $price);//将字符串转换为数组
        if (isset($str[1])) {//判断是否存在小数点
            $str2 = strlen($str[1]);//获取小数点位数
            if ($str2 <= 2) {//当小数点位数小于等于2 原样输出
                $data = $price;
            } else {
                $str4 = substr($str[1], 0, 2);//取出小数点后两位的值
                $str5 = substr($str[1], 0, 1);//取出小数点后1位的值
                if ($str4 == "00") {//当小数点后2为未00时直接+1
                    $str3 = "01";
                } elseif ($str5 == "0") {//当小数点后1为为0时直接最后1位+1
                    if (substr($str[1], 1, 1) + 1 !== 10) {
                        $str3 = (string)$str5 . (substr($str[1], 1, 1) + 1);
                    } else {
                        $str3 = substr($str[1], 0, 1) + 1;
                    }
                } else {//不满足上述条件直接+1
                    $str3 = substr($str[1], 0, 2) + 1;
                }
                if ($str3 == 100) {//当金额为X.99X直接整数+1
                    $data = ($str[0] + 1);
                } else {
                    $data = $str[0] . '.' . $str3;
                }
            }
        } else {
            $data = $price;
        }
        return $data;
    }


}